﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using web.core.ViewModels;
using web.core.Models;
using web.component;
using System.Configuration;
using web.data.entities;

namespace web.core.Controllers
{
    public class admProductController : baseController
    {
        #region mot so ham dung chung
        //tao ra link ao 
        public ActionResult getlink(string id)
        {
            string text = id;
            string outStr = Ustring.RemoveIllegalCharacters(id);
            return Json(outStr);
        }
        private ProductCategoyParamEntities ppnewEntities(global_const.E_PRODUCT_PARAM _key, string _desc)
        {
            var it = new ProductCategoyParamEntities()
            {
                key = ((int)_key == 0) ? "" : ((int)_key).ToString(),
                desc = _desc 
            };
            return it;
        }
        private List<ProductCategoyParamEntities> ListProductParam()
        {
            return new List<ProductCategoyParamEntities>(){
                    ppnewEntities(global_const.E_PRODUCT_PARAM.NORMAL, "---"),
                    ppnewEntities(global_const.E_PRODUCT_PARAM.HOT , "Sản phẩm nổi bật"),
                    ppnewEntities(global_const.E_PRODUCT_PARAM.NEW , "Sản phẩm mới"),
                    ppnewEntities(global_const.E_PRODUCT_PARAM.BEST , "Sản phẩm tốt nhất"),
                    ppnewEntities(global_const.E_PRODUCT_PARAM.FAVOR , "Sản phẩm ưa thích"),
                    ppnewEntities(global_const.E_PRODUCT_PARAM.SALE  , "Sản phẩm bán chạy"),
                    ppnewEntities(global_const.E_PRODUCT_PARAM.MOST_VIEW, "Sản phẩm xem nhiều")
                };
        }
        #endregion

        #region list_product_category
        public ActionResult list_product_category()
        {
            bool permission =false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_list_product_category(string text_search, int? parent)
        {
            int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            return control_list_product_category(text_search, parent, languageId);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_list_product_category(string text_search, int? parent,int? languageId)
        {
            var list_view = new ViewModels.PageListProductCategoryViewModels();
            
            list_view.page_list_product_category = productModels.getProductCategoryBuilder(text_search, parent, languageId);
            list_view.list_category_product_parent = productModels.getProductCategoryDropDownlist(null, languageId);
            list_view.list_language = languageModels.get_list_language();
            list_view.parent = parent??0;
            return PartialView("../Shared/product/control_list_product_category", list_view);
        }

        public ActionResult updateStatusProductCategory(string id)
        {
            web.data.entities.product_category cate = new data.entities.product_category();
            cate.category_id = int.Parse(id.Split(',')[0]);
            cate.category_status = byte.Parse(id.Split(',')[1]);
            Models.productModels.updateStatusProductCategory(cate);

            string outStr = "" + cate.category_status;
            return Json(outStr, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region delete_product_category
        //Xóa product category
        public ActionResult delete_product_category()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        public ActionResult control_delete_product_category(int? category_id, string text_search, int? parent, int? languageId)
        {
            if (category_id != null)
            {
                productModels.deleteProductCategory(category_id ?? 0);
            }

            ViewBag.result_message = "Xóa danh mục thành công";
            ViewBag.result = true;
            ViewBag.redirect = "/vi/admProduct/list_product_category";
            return PartialView("../Shared/control_redirect");
        }

        #endregion

        #region add/edit product_category:  edit_product_category
        //public ActionResult add_product_category()
        //{
        //    bool permission = false;
        //    InitPage(ref permission);
        //    ViewBag.permission = permission;
        //    return View();
        //}

        //[ChildActionOnly]
        //[HttpGet]
        //public ActionResult control_add_product_category(int? id)
        //{
        //    var list_langague = languageModels.get_list_language();
        //    List<web.data.entities.product_category_item> listItems = new List<data.entities.product_category_item>();
        //    foreach (var it in list_langague)
        //    {
        //        var cate_item = new web.data.entities.product_category_item();
        //        cate_item.language_id = it.language_id;
        //        cate_item.category_item_enable = true;

        //        listItems.Add(cate_item);
        //    }

        //    int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
        //    ViewBag.isAdd = true;
        //    var cate_view = new ViewModels.ProductCategoyViewModels();
        //    cate_view.category_status = 1;
        //    cate_view.listParent = productModels.getProductCategoryDropDownlist(null, languageId);
        //    cate_view.listItems = listItems;
        //    cate_view.listLanguage = list_langague;
        //    if (id != null)
        //    {
        //        cate_view.category_parent = id;
        //    }
        //    return PartialView("../Shared/product/control_product_category", cate_view);
        //}

        //[ChildActionOnly]
        //[HttpPost]
        //[ValidateInput(false)]
        //public ActionResult control_add_product_category(FormCollection collection)
        //{
        //    var cate_view = new ViewModels.ProductCategoyViewModels();
        //    TryUpdateModel(cate_view);

        //    if (cate_view.listItems.Count == 0 || string.IsNullOrEmpty(cate_view.listItems[0].category_name) || string.IsNullOrEmpty(cate_view.listItems[0].category_alias))
        //    {
        //        ViewBag.result_message = "Vui lòng nhập tên và alias cho danh mục";
        //        ViewBag.isAdd = true;
        //        ViewBag.result = false;
        //        return PartialView("../Shared/product/control_product_category", cate_view);
        //    }

        //    web.data.entities.product_category cate = new data.entities.product_category();
        //    cate.category_status = cate_view.category_status;
        //    cate.category_sort = cate_view.category_sort;
        //    cate.category_parent = cate_view.category_parent;
        //    cate.category_param = cate_view.category_param;

        //    //if category_name is Empty or null ==> remove that item 
        //    for (int i = cate_view.listItems.Count - 1; i >= 0; i--)
        //    {
        //        if (string.IsNullOrEmpty(cate_view.listItems[i].category_name) || string.IsNullOrEmpty(cate_view.listItems[i].category_alias))
        //        {
        //            cate_view.listItems.RemoveAt(i);
        //        }
        //    }

        //    int new_id = productModels.createProductCategory(cate, cate_view.listItems);

        //    if (new_id > 0)
        //    {
        //        ViewBag.result_message = "Thêm mới danh mục sản phẩm thành công.";
        //        ViewBag.result = true;
        //        ViewBag.redirect = "/vi/admProduct/list_product_category";
        //        return PartialView("../Shared/control_redirect");
        //    }
        //    else
        //    {
        //        ViewBag.result_message = "Thêm mới danh mục thất bại.";
        //        ViewBag.isAdd = true;
        //        ViewBag.result = false;
        //        return PartialView("../Shared/product/control_product_category", cate_view);
        //    }
        //}
       // #endregion

       // #region edit_product_category

        public ActionResult edit_product_category()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_edit_product_category(int? id)
        {
            var list_langague = languageModels.get_list_language();
            var listItems = new List<data.entities.product_category_item>();
            var list_Items_old = productModels.GetListProductCategoryItemsByCateID(id ?? 0, null);     //get all product category items with all languages
            int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);
            ViewModels.ProductCategoyViewModels cate_view;
            var lstParam = ListProductParam();
            if (list_Items_old.Count > 0)
            {
                //edit
                ViewBag.isAdd = false;
                if (list_Items_old.Count < list_langague.Count)
                {
                    for (int i = 0; i < list_langague.Count; i++)
                    {
                        var cate_item = new web.data.entities.product_category_item();
                        cate_item.language_id = list_langague[i].language_id;
                        cate_item.category_item_enable = true;

                        listItems.Add(cate_item);
                    }

                    for (int i = 0; i < list_Items_old.Count; i++)
                    {
                        for (int j = 0; j < listItems.Count; j++)
                        {
                            if (listItems[j].language_id == list_Items_old[i].language_id)
                            {
                                listItems.RemoveAt(j);
                                listItems.Add(list_Items_old[i]);
                            }
                        }
                    }
                }
                else
                {
                    listItems = list_Items_old;
                }

                var pro_cate = productModels.GetProductCategoryByID(id ?? 0);                   // get article category 

                cate_view = new ViewModels.ProductCategoyViewModels()
                {
                    category_status = pro_cate.category_status,
                    category_id = pro_cate.category_id,
                    category_param = pro_cate.category_param,
                    category_parent = pro_cate.category_parent,
                    category_sort = pro_cate.category_sort,
                    images = pro_cate.images,
                    image_display = Ufile.LoadImage(sUrl, pro_cate.images),
                    listParent = productModels.getProductCategoryDropDownlist(null, languageId),
                    listItems = listItems,
                    listLanguage = list_langague,
                    select_list_param = new SelectList(lstParam, "key", "desc")
                };
            }
            else
            {
                //add
                ViewBag.isAdd = true;
                //var list_langague = languageModels.get_list_language();
                //List<web.data.entities.product_category_item> listItems = new List<data.entities.product_category_item>();
                foreach (var it in list_langague)
                {
                    var cate_item = new web.data.entities.product_category_item();
                    cate_item.language_id = it.language_id;
                    cate_item.category_item_enable = true;

                    listItems.Add(cate_item);
                }

                //int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);               
                cate_view = new ViewModels.ProductCategoyViewModels() {
                    category_status = 1,
                    listParent = productModels.getProductCategoryDropDownlist(null, languageId),
                    listItems = listItems,
                    listLanguage = list_langague,
                    select_list_param = new SelectList(lstParam, "key", "desc")
                };
                var idp = Request.QueryString["idp"];
                if (idp != null)
                {
                    cate_view.category_parent = Convert.ToInt16(idp);
                }
            }

            return PartialView("../Shared/product/control_product_category", cate_view);
        }

        [ChildActionOnly]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult control_edit_product_category(FormCollection collection)
        {
            var cate_view = new ViewModels.ProductCategoyViewModels();
            TryUpdateModel(cate_view);

            bool is_edit = false;
            if (cate_view.category_id != 0 && cate_view.category_id != null)
                is_edit = true;

            if (cate_view.listItems.Count == 0 || string.IsNullOrEmpty(cate_view.listItems[0].category_name) || string.IsNullOrEmpty(cate_view.listItems[0].category_alias))
            {
                ViewBag.result_message = "Vui lòng nhập tên và alias cho danh mục";
                ViewBag.isAdd = is_edit;
                ViewBag.result = false;
                return PartialView("../Shared/product/control_product_category", cate_view);
            }
            bool isdel = is_edit ? true : false;
            web.data.entities.product_category cate = new data.entities.product_category() {
                category_status = cate_view.category_status,
                category_sort = cate_view.category_sort,
                category_parent = cate_view.category_parent,
                category_param = cate_view.category_param,
                category_id = cate_view.category_id ?? 0,
                //images = cate_view.images
                images = SaveImage(isdel, cate_view.images, cate_view.fileUpload, admin_const.E_IMG_TYPE.CATALOG, admin_const.E_IMG_THUMB.NO_THUMB),
            };
            //if (is_edit)
            //    cate.category_id = cate_view.category_id ?? 0;

            //if category_name is Empty or null ==> remove that item 
            for (int i = cate_view.listItems.Count - 1; i >= 0; i--)
            {
                if (string.IsNullOrEmpty(cate_view.listItems[i].category_name) || string.IsNullOrEmpty(cate_view.listItems[i].category_alias))
                {
                    cate_view.listItems.RemoveAt(i);
                    //delete category item
                    if (cate_view.listItems[i].category_item_id >0)
                    {
                        productModels.deleteProductCategoryItem(cate_view.listItems[i].category_item_id);
                    }                  
                }
            }
            if (is_edit)
            {
                productModels.editProductCategory(cate, cate_view.listItems);

                ViewBag.result_message = admin_const.UPDATE_OK;
                ViewBag.result = true;
                ViewBag.redirect = "/vi/admProduct/list_product_category";
                return PartialView("../Shared/control_redirect");
            }
            else {
                int new_id = productModels.createProductCategory(cate, cate_view.listItems);

                if (new_id > 0)
                {
                    ViewBag.result_message = admin_const.ADD_OK;
                    ViewBag.result = true;
                    ViewBag.redirect = "/vi/admProduct/list_product_category";
                    return PartialView("../Shared/control_redirect");
                }
                else
                {
                    ViewBag.result_message = admin_const.ADD_FAIL;
                    ViewBag.isAdd = true;
                    ViewBag.result = false;
                    return PartialView("../Shared/product/control_product_category", cate_view);
                }
            }
        }

        #endregion

        #region list_product
        public ActionResult list_product()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_list_product(string text_search, int? cateId, string showStyle)
        {
            //int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            int? languageId = null;
            int currentPage = 1;
            int pageSize = admin_const.PAGE_LIST_SIZE;  //default pagesize = 10
            if (string.IsNullOrEmpty(showStyle))
            {
                showStyle = "grid";                 //default style is grid
            }
            ViewBag.style = showStyle;
            ViewBag.orderBy = "created_date"; //default order by created date
            ViewBag.orderType = "desc"; //default sort by desc
            return control_list_product(text_search, cateId, languageId, currentPage, pageSize, "created_date", "desc", showStyle);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_list_product(string text_search, int? cateId, int? languageId, int? page, int? pageSize, string orderBy, string orderType, string showStyle)
        {
            page = Request.QueryString["page"] != null ? int.Parse(Request.QueryString["page"].ToString()) : 1;

            var total = 0;
            List<SelectListItem> sizeDrop = GetSizePagingPublic(pageSize ?? admin_const.PAGE_LIST_SIZE);

            List<SelectListItem> orderDrop = new List<SelectListItem>();
            orderDrop.AddRange(new SelectListItem[] { 
                            new SelectListItem{Selected=orderBy=="product_name"?true:false, Text = "Tên sản phẩm", Value = "product_name" },
                            new SelectListItem{Selected=orderBy=="price"?true:false, Text = "Giá", Value = "price" },
                            new SelectListItem{Selected=orderBy=="sales"?true:false, Text = "Bán", Value = "sales" },
                            new SelectListItem{Selected=orderBy=="quantity"?true:false, Text = "Số lượng", Value = "quantity" }
                        });

            var list_view = new ViewModels.AdmPageListProductViewModels();
            TryUpdateModel(list_view);
            if (list_view.languageId != null)
            {
                languageId = list_view.languageId;
            }
            list_view.page_list_product = productModels.GetListProductByCategoryIDAdm(text_search, languageId, cateId, (page ?? 1), 
                                                                            (pageSize ?? admin_const.PAGE_LIST_SIZE), orderBy, orderType, out total);
            list_view.list_category_product = productModels.getProductCategoryDropDownlist(null, languageId);
            list_view.list_language = languageModels.get_list_language();
            list_view.text_search = text_search;
            list_view.total = total;
            list_view.list_pagesize = sizeDrop;
            list_view.pagesize = pageSize ?? 10;
            list_view.list_order = orderDrop;
            list_view.orderBy = orderBy;
            list_view.orderType = orderType;
            list_view.showStyle = showStyle;
            return PartialView("../Shared/product/control_list_product", list_view);
        }

        public ActionResult updateStatusProduct(string id)
        {
            web.data.entities.product pro = new data.entities.product();
            pro.product_id = int.Parse(id.Split(',')[0]);
            pro.product_status = byte.Parse(id.Split(',')[1]);
            Models.productModels.updateStatusProduct(pro);

            string outStr = "" + pro.product_status;
            return Json(outStr, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region add_product -- removed
        //public ActionResult add_product()
        //{
        //    bool permission = false;
        //    InitPage(ref permission);
        //    ViewBag.permission = permission;
        //    return View();
        //}

        //[ChildActionOnly]
        //[HttpGet]
        //public ActionResult control_add_product(int? id)
        //{
        //    var list_langague = languageModels.get_list_language();
        //    List<web.data.entities.product_item> listItems = new List<data.entities.product_item>();
        //    foreach (var it in list_langague)
        //    {
        //        var pro_item = new web.data.entities.product_item();
        //        pro_item.language_id = it.language_id;
        //        pro_item.product_item_enable = true;

        //        listItems.Add(pro_item);
        //    }
        //    //List<web.data.entities.product_images> listImages = new List<data.entities.product_images>();
        //    //for (int i = 0; i < 5; i++)
        //    //{
        //    //    //add default 5 images for 1 product
        //    //    web.data.entities.product_images img = new data.entities.product_images()
        //    //    {
        //    //        images_enable = true
        //    //    };
        //    //    listImages.Add(img);
        //    //}
            
        //    int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
        //    ViewBag.isAdd = true;
        //    string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);

        //    var pro_view = new ViewModels.AdmProductViewModels();
        //    pro_view.product_status = 1;
        //    pro_view.listCategory = productModels.getProductCategoryDropDownlist(null, languageId);
        //    pro_view.listItems = listItems;
        //    pro_view.listLanguage = list_langague;
        //   // pro_view.listImages = listImages;

        //    pro_view.image_display = Ufile.LoadImage(sUrl, "");

        //    if (id != null)
        //    {
        //        //id is category_id
        //        pro_view.cate_id = id;
        //    }
        //    return PartialView("../Shared/product/control_product", pro_view);
        //}

        //[ChildActionOnly]
        //[HttpPost]
        //[ValidateInput(false)]
        //public ActionResult control_add_product(FormCollection collection)
        //{
        //    int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);


        //    var pro_view = new ViewModels.AdmProductViewModels();
        //    TryUpdateModel(pro_view);

        //    if (pro_view.listItems.Count == 0 || string.IsNullOrEmpty(pro_view.listItems[0].product_name) || string.IsNullOrEmpty(pro_view.listItems[0].product_alias))
        //    {
        //        var list_langague = languageModels.get_list_language();
        //        List<web.data.entities.product_item> listItems = new List<data.entities.product_item>();
        //        foreach (var it in list_langague)
        //        {
        //            var pro_item = new web.data.entities.product_item();
        //            pro_item.language_id = it.language_id;
        //            pro_item.product_item_enable = true;

        //            listItems.Add(pro_item);
        //        }
        //        pro_view.listLanguage = list_langague;
        //        pro_view.listCategory = productModels.getProductCategoryDropDownlist(null, languageId);
        //        pro_view.listItems = listItems;
        //        ViewBag.result_message = "Vui lòng nhập tên sản phẩm và alias cho sản phẩm";
        //        ViewBag.isAdd = true;
        //        ViewBag.result = false;
        //        return PartialView("../Shared/product/control_product", pro_view);
        //    }
        //    bool isdel = false;// pro_view.product_id != 0 ? true : false;
        //    string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);

        //    web.data.entities.product pro = new data.entities.product();
        //    pro.product_status = pro_view.product_status;
        //    pro.created_date = DateTime.UtcNow;
        //    //pro.images = pro_view.images;
        //    pro.images = SaveImage(isdel, pro_view.images, pro_view.fileUpload, admin_const.E_IMG_TYPE.PRODUCT, admin_const.E_IMG_THUMB.NO_THUMB);
        //    pro_view.image_display = Ufile.LoadImage(sUrl, pro.images);

        //    //if category_name is Empty or null ==> remove that item 
        //    for (int i = pro_view.listItems.Count - 1; i >= 0; i--)
        //    {
        //        if (string.IsNullOrEmpty(pro_view.listItems[i].product_name) || string.IsNullOrEmpty(pro_view.listItems[i].product_alias))
        //        {
        //            pro_view.listItems.RemoveAt(i);
        //        }
        //    }

        //    ////if images is Empty or null ==> remove that images
        //    //for (int i = pro_view.listImages.Count - 1; i >= 0; i--)
        //    //{
        //    //    if (string.IsNullOrEmpty(pro_view.listImages[i].images))
        //    //    {
        //    //        pro_view.listImages.RemoveAt(i);
        //    //    }
        //    //}

        //    List<web.data.entities.product_ref_category> list_ref = new List<data.entities.product_ref_category>();
        //    if (!string.IsNullOrEmpty(pro_view.arr_product_category) && pro_view.arr_product_category.Contains(","))
        //    {
        //        var arr_cate = pro_view.arr_product_category.Split(',');
        //        int[] arr_cate_int = arr_cate.Select(n => Convert.ToInt32(n)).ToArray();
        //        foreach (var it in arr_cate_int)
        //        {
        //            web.data.entities.product_ref_category pro_ref = new data.entities.product_ref_category()
        //            {
        //                category_id = it
        //            };
        //            list_ref.Add(pro_ref);
        //        }
        //    }

        //    int new_id = productModels.createProduct(pro, pro_view.listItems, list_ref, pro_view.listImages);

        //    if (new_id > 0)
        //    {
        //        ViewBag.result_message = "Thêm mới sản phẩm thành công.";
        //        ViewBag.result = true;
        //        ViewBag.redirect = "/vi/admProduct/list_product";
        //        return PartialView("../Shared/control_redirect");
        //    }
        //    else
        //    {
        //        var list_langague = languageModels.get_list_language();
        //        List<web.data.entities.product_item> listItems = new List<data.entities.product_item>();
        //        foreach (var it in list_langague)
        //        {
        //            var pro_item = new web.data.entities.product_item();
        //            pro_item.language_id = it.language_id;
        //            pro_item.product_item_enable = true;

        //            listItems.Add(pro_item);
        //        }
        //        pro_view.listLanguage = list_langague;
        //        pro_view.listCategory = productModels.getProductCategoryDropDownlist(null, languageId);
        //        pro_view.listItems = listItems;
        //        pro_view.image_display = Ufile.LoadImage(sUrl, "");
        //        ViewBag.result_message = "Thêm mới sản phẩm thất bại.";
        //        ViewBag.isAdd = true;
        //        ViewBag.result = false;
        //        return PartialView("../Shared/product/control_product", pro_view);
        //    }
        //}
        #endregion

        #region edit_product
        public ActionResult edit_product()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_edit_product(int? id)
        {
            int itemid = id ?? 0;
            if (itemid == 0)
                ViewBag.isAdd = true;
            else
                ViewBag.isAdd = false;
            var pro_view = loadProductViewModels(id);

            return PartialView("../Shared/product/control_product", pro_view);
        }

        public AdmProductViewModels loadProductViewModels(int? id)
        {
            var list_langague = languageModels.get_list_language();
            List<web.data.entities.product_item> listItems = new List<data.entities.product_item>();

            string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);
            int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
            ViewModels.AdmProductViewModels pro_view;


            var pro = productModels.GetProductByID(id ?? 0);
            if (pro != null)
            {
                ViewBag.isAdd = false;
                var list_items_old = productModels.GetListProductItemsByProductID(id ?? 0, null);
                listItems = list_items_old;

                //if (list_items_old.Count < list_langague.Count)
                //{
                for (int i = 0; i < list_langague.Count; i++)
                {
                    bool is_exist_it = false;
                    for (int j = 0; j < list_items_old.Count; j++)
                    {
                        if (listItems[j].language_id == list_langague[i].language_id)
                            is_exist_it = true;
                    }
                    // them item theo ngon ngu
                    if (is_exist_it == false)
                    {
                        var pro_item = new web.data.entities.product_item()
                        {
                            language_id = list_langague[i].language_id,
                            product_item_enable = true
                        };

                        listItems.Add(pro_item);
                    }

                }

                //for (int i = 0; i < list_items_old.Count; i++)
                //{
                //    for (int j = 0; j < listItems.Count; j++)
                //    {
                //        if (listItems[j].language_id == list_items_old[i].language_id)
                //        {
                //            listItems.RemoveAt(j);
                //            listItems.Add(list_items_old[i]);
                //        }
                //    }
                //}
                //}
                //else
                //{

                //}
                listItems = listItems.OrderBy(p => p.language_id).ToList();

                //var list_img = productModels.GetListProductImagesByProductID(id ?? 0);
                //if (list_img.Count < 5 && list_img.Count>=0)
                //{
                //    for (int i = 0; i < (5-list_img.Count); i++)
                //    {
                //        //add default 5 images for 1 product
                //        web.data.entities.product_images img = new data.entities.product_images()
                //        {
                //            images_enable = true
                //        };
                //        list_img.Add(img);
                //    }
                //}


                pro_view = new ViewModels.AdmProductViewModels()
                {
                    product_status = pro.product_status,
                    images = pro.images,
                    image_display = Ufile.LoadImage(sUrl, pro.images),
                    price = pro.price,
                    product_id = pro.product_id,
                    old_price = pro.old_price,
                    created_date = pro.created_date,
                    modify_by = pro.modify_by,
                    modify_date = pro.modify_date,
                    quantity = pro.quantity,
                    sales = pro.sales,
                    tax = pro.tax,
                    listCategory = productModels.getProductCategoryDropDownlist(null, languageId),
                    //listImages = list_img,
                    listItems = listItems,
                    listLanguage = list_langague
                };

                //danh muc sp
                var list_arr = productModels.GetListCategoryByProductID(id ?? 0).ToList();
                for (int i = 0; i < list_arr.Count(); i++)
                {
                    pro_view.arr_product_category = pro_view.arr_product_category + list_arr[i].ToString() + ",";
                }
                if (pro_view.arr_product_category != null)
                {
                    if (pro_view.arr_product_category.EndsWith(","))
                    {
                        pro_view.arr_product_category = pro_view.arr_product_category.Substring(0, pro_view.arr_product_category.LastIndexOf(","));
                    }
                }

                //tags
                var arrtag =  productModels.tag_getby_productid(  pro.product_id);
                string[] tags = new string[arrtag.Count];
                for (int i = 0; i < arrtag.Count; i++)
                {
                    tags[i] = arrtag[i].tag;
                }
                pro_view.tags  = string.Join(",", tags);

            }
            else
            {
                ViewBag.isAdd = true;
                //var list_langague = languageModels.get_list_language();
                //  List<web.data.entities.product_item> listItems = new List<data.entities.product_item>();
                foreach (var it in list_langague)
                {
                    var pro_item = new web.data.entities.product_item()
                    {
                        language_id = it.language_id,
                        product_item_enable = true
                    };
                    listItems.Add(pro_item);
                }
                //List<web.data.entities.product_images> listImages = new List<data.entities.product_images>();
                //for (int i = 0; i < 5; i++)
                //{
                //    //add default 5 images for 1 product
                //    web.data.entities.product_images img = new data.entities.product_images()
                //    {
                //        images_enable = true
                //    };
                //    listImages.Add(img);
                //}

                // int? languageId = languageModels.GetLanguageIDbyUrl(Request.Url.PathAndQuery);
                //ViewBag.isAdd = true;
                //string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);

                pro_view = new ViewModels.AdmProductViewModels()
                {
                    product_status = 1,
                    listCategory = productModels.getProductCategoryDropDownlist(null, languageId),
                    listItems = listItems,
                    listLanguage = list_langague,
                    // listImages = listImages,
                    image_display = Ufile.LoadImage(sUrl, ""),
                    price = 0,
                    old_price = 0,
                    quantity = 10,
                    sales = 0,
                    tax = 0,
                };
                //if (id != null)
                //{
                //    //id is category_id
                //    pro_view.cate_id = id;
                //}
            }

            return pro_view;
        }

        [ChildActionOnly]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult control_edit_product(FormCollection collection)
        {
            var pro_view = new ViewModels.AdmProductViewModels();
            TryUpdateModel(pro_view);

            bool is_edit = false;
            if (pro_view.product_id != 0 && pro_view.product_id != null)
                is_edit = true; 

            var count = pro_view.listItems.Count;

            //if title is Empty or null ==> remove that item 
            for (int i = pro_view.listItems.Count - 1; i >= 0; i--)
            {
                var aitem = pro_view.listItems[i];
                if (string.IsNullOrEmpty(aitem.product_name) || string.IsNullOrEmpty(aitem.product_alias))
                {
                    //delete product item
                    if (is_edit)
                        productModels.deleteProductItem(pro_view.listItems[i].product_item_id);
                    pro_view.listItems.RemoveAt(i);
                }
            }

            ////if images is Empty or null ==> remove that images
            //for (int i = pro_view.listImages.Count - 1; i >= 0; i--)
            //{
            //    if (string.IsNullOrEmpty(pro_view.listImages[i].images))
            //    {
            //        pro_view.listImages.RemoveAt(i);
            //        //delete product images
            //        if (pro_view.listImages[i].images_id >0)
            //        {
            //            productModels.deleteProductImages(pro_view.listImages[i].images_id);
            //        }
            //    }
            //}

            if (pro_view.listItems.Count <= 0 || string.IsNullOrEmpty(pro_view.listItems[0].product_name) || string.IsNullOrEmpty(pro_view.listItems[0].product_alias))
            {
                pro_view = loadProductViewModels(pro_view.product_id);

                ViewBag.result_message = "Vui lòng nhập tên và alias cho sản phẩm";
                //ViewBag.isAdd = false;
                ViewBag.result = false;
                return PartialView("../Shared/product/control_product", pro_view);
            }
            string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);
            //bool isdel = true;// pro_view.product_id != 0 ? true : false;
            bool isdel = is_edit ? true : false;

            var pro = new data.entities.product() {
                product_status = pro_view.product_status,
                // images = pro_view.images, 
                images = SaveImage(isdel, pro_view.images, pro_view.fileUpload, admin_const.E_IMG_TYPE.PRODUCT, admin_const.E_IMG_THUMB.NO_THUMB),
                //pro_view.image_display = Ufile.LoadImage(sUrl, images),
                price = pro_view.price,
                product_id = (int)(pro_view.product_id??0),
                old_price = pro_view.old_price,
                modify_by = int.Parse(Session["user_id"].ToString()),
                modify_date = Udate_time.GetCurrentDateTime(),
                quantity = pro_view.quantity,
                sales = pro_view.sales,
                tax = pro_view.tax,
            };
            if (!is_edit)
                pro.created_date = Udate_time.GetCurrentDateTime();

            //delete all ref by articleID
            productModels.DeleteAllProductRefByProductID(pro_view.product_id ?? 0);

            List<web.data.entities.product_ref_category> list_ref = new List<data.entities.product_ref_category>();
            if (!string.IsNullOrEmpty(pro_view.arr_product_category))
            {
                var arr_cate = pro_view.arr_product_category.Split(',');
                int[] arr_cate_int = arr_cate.Select(n => Convert.ToInt32(n)).ToArray();
                foreach (var it in arr_cate_int)
                {
                    web.data.entities.product_ref_category pro_ref = new data.entities.product_ref_category()
                    {
                        category_id = it
                    };
                    list_ref.Add(pro_ref);
                }
            }


            //tags
            //otag.Delete(id);
            var lstTag = new List<product_tag>();            
            if (!string.IsNullOrEmpty(pro_view.tags))
            {
                var strTag = pro_view.tags.Trim();
                if (strTag.Length > 0)
                {
                    string[] tags = strTag.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string tag in tags)
                    {
                        var dvtag = new product_tag()
                        {
                            product_id = (int)(pro_view.product_id ?? 0),
                            tag = tag.Trim().ToLowerInvariant(),
                            link = Ustring.RemoveIllegalCharacters(tag.Trim())
                        };
                        lstTag.Add(dvtag);
                    }
                }
            }

            if (is_edit)
            {
                productModels.editProduct(pro, pro_view.listItems, list_ref, pro_view.listImages, lstTag);

                ViewBag.result_message = admin_const.UPDATE_OK;
                ViewBag.result = true;
                ViewBag.redirect = "/vi/admProduct/edit_product/" + pro.product_id;
               // ViewBag.redirect = "/vi/admProduct/list_product";
                return PartialView("../Shared/control_redirect");
            }
            else {
                int new_id = productModels.createProduct(pro, pro_view.listItems, list_ref, pro_view.listImages, lstTag);

                if (new_id > 0)
                {
                    ViewBag.result_message = admin_const.ADD_OK;
                    ViewBag.result = true;
                    //return PartialView("../Shared/product/control_product", pro_view); // quay ve de edit
                    ViewBag.redirect = "/vi/admProduct/edit_product/" + new_id;
                    return PartialView("../Shared/control_redirect");
                }
                else
                {
                    //var list_langague = languageModels.get_list_language();
                    //List<web.data.entities.product_item> listItems = new List<data.entities.product_item>();
                    //foreach (var it in list_langague)
                    //{
                    //    var pro_item = new web.data.entities.product_item();
                    //    pro_item.language_id = it.language_id;
                    //    pro_item.product_item_enable = true;

                    //    listItems.Add(pro_item);
                    //}
                    //pro_view.listLanguage = list_langague;
                    //pro_view.listCategory = productModels.getProductCategoryDropDownlist(null, languageId);
                    //pro_view.listItems = listItems;
                    //pro_view.image_display = Ufile.LoadImage(sUrl, ""); 
                    ViewBag.result_message = admin_const.ADD_FAIL;
                    //ViewBag.isAdd = true;
                    ViewBag.result = false;
                    return PartialView("../Shared/product/control_product", pro_view);
                }
            }
        }
        #endregion

        #region delete_product
        //Xóa product 
        public ActionResult delete_product()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        public ActionResult control_delete_product(int? product_id)
        {
            if (product_id != null)
            {
                productModels.deleteProduct(product_id ?? 0);
            }

            ViewBag.result_message = "Xóa sản phẩm thành công";
            ViewBag.result = true;
            ViewBag.redirect = "/vi/admProduct/list_product";
            return PartialView("../Shared/control_redirect");
        }
        #endregion

        #region product images
        public ActionResult product_images()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_product_images(int? id)
        {
            var pid = id ?? 0;
            var lst = productModels.GetListProductImagesByProductID(pid);
            string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);
            foreach (var it in lst)
                it.images = Ufile.LoadImage(sUrl, it.images);

            var page_view = new ViewModels.ProductImageViewModels()
            {
                listImages = lst,
                product_id = pid
            };

            return PartialView("../Shared/product/control_product_images", page_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_product_images( )
        {
            var item_view = new ViewModels.ProductImageViewModels();
            TryUpdateModel(item_view);

            //upload image
            var upload_image = Request.Form["upload_image"];
            if (!string.IsNullOrEmpty(upload_image) && item_view.product_id != 0)
            {
                if (item_view.fileUpload1 != null && item_view.fileUpload1.ContentLength > 0 &&
                    item_view.fileUpload2 != null && item_view.fileUpload2.ContentLength > 0)
                {

                    string iName = item_view.fileUpload2.FileName;
                    string iSmall = string.Format("_thumb_{0}", item_view.product_id);
                    string iFull = string.Format("_large_{0}", item_view.product_id);
                    var item = new data.entities.product_images()
                    {
                        images_thumb = SaveImage(false, iSmall, item_view.fileUpload1, admin_const.E_IMG_TYPE.PRODUCT_IMG, admin_const.E_IMG_THUMB.NO_THUMB),
                        images = SaveImage(false, iFull, item_view.fileUpload2, admin_const.E_IMG_TYPE.PRODUCT_IMG, admin_const.E_IMG_THUMB.NO_THUMB),
                        images_name = iName,
                        images_enable = true,
                        product_id = item_view.product_id
                    };
                    var iUp = productModels.product_img_add(item);
                    if (iUp > 0)
                    {
                        ViewBag.result_message = admin_const.UPDATE_OK;
                        ViewBag.result = true;
                    }
                }
            }
            //delete image
            var lstdelete = Request.Form["is_delete"];
            if (!string.IsNullOrEmpty(lstdelete))
            {
                var arr = lstdelete.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var iterator in arr)
                {
                    if (iterator != "false")
                        productModels.deleteProductImages(Convert.ToInt16(iterator));
                }
            } 

            var lst = productModels.GetListProductImagesByProductID(item_view.product_id);
            string sUrl = siteSettingSingleModels.GetConfig(global_const.WEBSITE_URL);
            foreach (var it in lst)
                it.images = Ufile.LoadImage(sUrl, it.images);

            item_view.listImages = lst;

            //delete images 
            return PartialView("../Shared/product/control_product_images", item_view);
        }
        #endregion

        #region product relate
        public ActionResult product_relate()
        {
            bool permission = false;
            InitPage(ref permission);
            ViewBag.permission = permission;
            return View();
        }

        [ChildActionOnly]
        public ActionResult control_product_relate(int? id, string text_search, int? cateId, int? languageId, int? page, int? pageSize)
        {
            var pid = id ?? 0;
            page = Request.QueryString["page"] != null ? int.Parse(Request.QueryString["page"].ToString()) : 1;

            //var total = 0; 
            var page_view = new ViewModels.ProductRelateViewModels()
            {
                product_id = pid
            };
            TryUpdateModel(page_view);
            if (page_view.languageId != null)
            {
                languageId = page_view.languageId;
            }
            else
                languageId = global_const.LANGUAGE_ID_DEFAULT;

            var save_change = Request.Form["save_change"];
            if (!string.IsNullOrEmpty(save_change))
            {
                int product_id = page_view.product_id;
                //remove from relate
                var lstdelete = Request.Form["is_delete"];
                if (!string.IsNullOrEmpty(lstdelete))
                {
                    var arr = lstdelete.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var iterator in arr)
                    {
                        if (iterator != "false")
                            productModels.product_relate_delete(product_id, Convert.ToInt16(iterator));
                    }
                }
                //add to relate 
                var lstadd = Request.Form["is_add"];
                if (!string.IsNullOrEmpty(lstadd))
                {
                    var arr = lstadd.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var iterator in arr)
                    {
                        if (iterator != "false") {
                            var pritem = new product_relate() {
                                product_id_a = product_id,
                                product_id_b = Convert.ToInt16(iterator)
                            };
                            if (pritem.product_id_a != pritem.product_id_b) // no ko tu relate den no :)
                                productModels.product_relate_add(pritem); 
                        }
                    }
                }

            }

            var lstCate = productModels.getProductCategoryDropDownlist(null, languageId);
            var lstLang = languageModels.get_list_language();
            var sizeDrop = GetSizePagingPublic(pageSize ?? admin_const.PAGE_LIST_SIZE);

            page_view.list_relate = productModels.GetListProductRelated(pid, -1); // get all
            page_view.list_not_relate = productModels.GetListProductNotRelate(pid, text_search, languageId, cateId, (page ?? 1), (pageSize ?? admin_const.PAGE_LIST_SIZE));
            page_view.list_category_product = new SelectList(lstCate, "category_id", "category_name");            
            page_view.list_language = new SelectList(lstLang, "language_id", "language_desc");
            page_view.text_search = text_search;
          //  list_view.total = total;
            page_view.list_pagesize = sizeDrop;
            page_view.pagesize = pageSize ?? 10;
            //list_view.list_order = orderDrop;
            //list_view.orderBy = orderBy;
            //list_view.orderType = orderType;
            //list_view.showStyle = showStyle;

            return PartialView("../Shared/product/control_product_relate", page_view);
        } 
        #endregion

    }
} 
